<template>
  <div class="news-page" :class="theme">

    <!-- ⭐ 固定顶部（包含 NavBar + 日期栏 + 跑马灯） -->
    <div class="header-fixed">
      <van-nav-bar
        title="加密货币新闻时间线"
        left-arrow
        @click-left="$router.back()"
      >
        <template #right>
          <div class="theme-toggle" @click="toggleTheme">
            <!-- ☀ 白天 -->
            <svg v-if="theme === 'light'" class="sun" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="5" fill="#facc15" />
              <g stroke="#facc15" stroke-width="2">
                <line x1="12" y1="1" x2="12" y2="4" />
                <line x1="12" y1="20" x2="12" y2="23" />
                <line x1="1" y1="12" x2="4" y2="12" />
                <line x1="20" y1="12" x2="23" y2="12" />
                <line x1="4" y1="4" x2="6" y2="6" />
                <line x1="18" y1="18" x2="20" y2="20" />
                <line x1="4" y1="20" x2="6" y2="18" />
                <line x1="18" y1="6" x2="20" y2="4" />
              </g>
            </svg>

            <!-- 🌙 夜间 -->
            <svg v-else class="moon" viewBox="0 0 24 24">
              <path
                fill="#cbd5e1"
                d="M21 12.79A9 9 0 0111.21 3a7 7 0 100 14A9 9 0 0021 12.79z"
              />
            </svg>
          </div>
        </template>
      </van-nav-bar>

      <!-- 日期栏 + 跑马灯 -->
      <div class="date-bar">
        <div class="date-left">今天 · {{ today }}</div>

        <div class="marquee-box">
          <div class="marquee-track">

            <div class="marquee-inner">
              <span
                v-for="c in coins"
                :key="c.symbol"
                class="marq-item"
              >
                <!-- ⭐ 价格 + 涨跌幅一起变色 -->
                <span :class="{ up: c.change > 0, down: c.change < 0 }">
                  {{ c.symbol }} {{ c.price }}
                  ({{ formatChange(c.change) }})
                </span> |
              </span>
            </div>

            <div class="marquee-inner">
              <span
                v-for="c in coins"
                :key="c.symbol + '_2'"
                class="marq-item"
              >
                <!-- ⭐ 第二份也同步变色 -->
                <span :class="{ up: c.change > 0, down: c.change < 0 }">
                  {{ c.symbol }} {{ c.price }}
                  ({{ formatChange(c.change) }})
                </span> |
              </span>
            </div>

          </div>
        </div>
      </div>
    </div>

    <!-- ⭐ 内容滚动区域 -->
    <div class="content-scroll" ref="scrollBox">

      <div class="back-top" v-show="showBackTop" @click="scrollTop">
        ↑
      </div>

      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <div class="timeline">

          <div v-for="item in list" :key="item.link" class="timeline-item">
            <div class="timeline-left">
              <div class="dot"></div>
              <div class="line"></div>
            </div>

            <div class="timeline-content">
              <div class="time">{{ item.pubDate }}</div>
              <div class="title">{{ item.title }}</div>
              <div class="desc">{{ item.fullText }}</div>
            </div>
          </div>

        </div>
      </van-pull-refresh>

    </div>

  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";

/* ---------------------- 主题模式 ---------------------- */
const theme = ref(localStorage.getItem("theme") || "light");

function toggleTheme() {
  theme.value = theme.value === "light" ? "dark" : "light";
  localStorage.setItem("theme", theme.value);
}

/* ---------------------- 日期 ---------------------- */
const today = new Date().toLocaleDateString();

/* ---------------------- 新闻 ---------------------- */
const list = ref([]);
const refreshing = ref(false);

function parseRSS(xmlStr) {
  const xml = new DOMParser().parseFromString(xmlStr, "text/xml");
  const items = [...xml.querySelectorAll("item")].slice(0, 30);

  return items.map((item) => {
    const pubStr = item.querySelector("pubDate")?.textContent || "";
    const pub = new Date(pubStr);

    let text = item.querySelector("description")?.textContent || "";
    text = text.replace(/<[^>]+>/g, "").trim();
    if (text.length > 200) text = text.slice(0, 200) + "...";

    return {
      title: item.querySelector("title")?.textContent || "",
      link: item.querySelector("link")?.textContent || "",
      pubDate: pubStr.replace(/\+0000/g, ""),
      timestamp: pub.getTime(),
      fullText: text,
    };
  });
}

async function loadRSS() {
  const url =
    "https://api.allorigins.win/raw?url=" +
    encodeURIComponent("https://www.coindesk.com/arc/outboundfeeds/rss/");
  const res = await axios.get(url, { responseType: "text" });
  return parseRSS(res.data);
}

async function onRefresh() {
  refreshing.value = true;
  list.value = await loadRSS();
  refreshing.value = false;
}

/* ---------------------- 币价 WebSocket ---------------------- */
const coins50 = [
  "BTC","ETH","TRUMP","BNB","SOL","XRP","CHZ","DOGE","ADA","AVAX",
  "TRX","DOT","LINK","MATIC","SHIB","TON","BCH","LTC","UNI","ICP",
  "NEAR","XLM","ETC","XMR","FIL","APT","HBAR","VET","ARB",
  "OP","RUNE","IMX","INJ","ATOM","SUI","LDO","STX","MKR","QNT",
  "ALGO","AAVE","THETA","EGLD","XTZ","FLOW","SAND","AXS","GRT","USDC"
];

const coins = ref(coins50.map(s => ({
  symbol: s.replace("USDT", ""),
  price: "...",
  change: 0,
})));

let ws;
function connectWS() {
  const streams = coins50.map(s => s.toLowerCase() + "usdt@ticker").join("/");
  ws = new WebSocket(
    `wss://stream.binance.com:9443/stream?streams=${streams}`
  );

  ws.onmessage = (msg) => {
    const d = JSON.parse(msg.data)?.data;
    if (!d) return;

    const sym = d.s.replace("USDT", "");
    const coin = coins.value.find(c => c.symbol === sym);
    if (!coin) return;

    coin.price = Number(d.c).toFixed(4);
    coin.change = Number(d.P);
  };

  ws.onclose = () => setTimeout(connectWS, 1500);
}

function formatChange(n) {
  return (n > 0 ? "+" : "") + n.toFixed(2) + "%";
}

/* ---------------------- 返回顶部 ---------------------- */
const scrollBox = ref(null);
const showBackTop = ref(false);

function scrollTop() {
  scrollBox.value.scrollTo({ top: 0, behavior: "smooth" });
}

function watchScroll() {
  scrollBox.value.addEventListener("scroll", () => {
    showBackTop.value = scrollBox.value.scrollTop > 300;
  });
}

onMounted(async () => {
  list.value = await loadRSS();
  connectWS();
  watchScroll();
});
</script>

<style scoped>
.news-page.light { background: #f6f6f6; color: #222; }
.news-page.dark  { background: #181818; color: #ddd; }

.header-fixed {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 99;
  background: inherit;
}

.content-scroll {
  position: relative;
  height: calc(100vh - 0px);
  margin-top: 96px;
  overflow-y: auto;
}

.back-top {
  position: fixed;
  right: 14px;
  bottom: 90px;
  width: 38px;
  height: 38px;
  background: #ffcc00;
  color: #000;
  font-size: 20px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 888;
  box-shadow: 0 2px 8px rgba(0,0,0,0.25);
  cursor: pointer;
}

.theme-toggle { width: 26px; height: 26px; }
.sun, .moon { width: 26px; height: 26px; }

/* 日期栏 */
.date-bar {
  position: relative;
  display: flex;
  align-items: center;
  padding: 10px 12px;
  background: #fff;
}
.news-page.dark .date-bar { background: #222; }
.date-left { font-weight: bold; }

/* 跑马灯 */
.marquee-box {
  position: absolute;
  left: 150px;
  right: 10px;
  height: 20px;
  overflow: hidden;
}
.marquee-track {
  display: inline-flex;
  white-space: nowrap;
  animation: scroll-left 700s linear infinite;
}
.marq-item { padding-right: 14px; }

.up   { color: #16c784 !important; }
.down { color: #ea3943 !important; }

@keyframes scroll-left {
  0%   { transform: translateX(0);}
  100% { transform: translateX(-100%);}
}

/* 时间线 */
.timeline { padding: 0 16px; }
.timeline-item { display: flex; padding-bottom: 24px; }
.timeline-left {
  width: 24px;
  display: flex;
  align-items: center;
  flex-direction: column;
}
.dot { width: 10px; height: 10px; background:#ffc400; border-radius:50%; margin-top:6px; }
.line { flex:1; width:2px; background:#e3e3e3; }
.time { font-size:12px; color:#999; }
.title { font-size:15px; font-weight:bold; }
.desc { font-size:14px; line-height:1.55; }
</style>
